package ru.compscicenter.uno.view;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class ImageButton extends JComponent {
    private BufferedImage image;
    private final String buttonName;
    private static final String DIR = "res/img/buttons/";
    private static final String FOCUSED_POSTFIX = "_focused";

    public ImageButton(String buttonName) {
        this.buttonName = buttonName;
        loadImage(composePath());

        addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                loadImage(composeFocusedPath());
                repaint();
            }

            @Override
            public void mouseExited(MouseEvent e) {
                loadImage(composePath());
                repaint();
            }
        });
    }

    /**
     * пропорции исходной картинки
     * @return отношение ширины к высоте
     */
    public float getProportionOfOriginalImage(){
       return image.getWidth()/image.getHeight();
    }

    private void loadImage(String path) {
        try {
            image = ImageIO.read(new File(path));
        } catch (IOException e) {
            //todo ?
            System.err.println("error: " + e.getMessage() + " " + e);
        }
    }
    
    private String composePath(){
        return DIR + buttonName + ".png";
    }

    private String composeFocusedPath(){
        return DIR + buttonName + FOCUSED_POSTFIX + ".png";
    }

    @Override
    public void paintComponent(Graphics g) {
        int w = getWidth();
        int h = getHeight();
        g.drawImage(image, 0, 0, w, h, null);
    }
}
